package com.example.tech.folio.controller;

import com.example.tech.folio.mapper.ProfileMapper;
import com.example.tech.folio.pojo.entity.Profile;
import com.example.tech.folio.pojo.param.ProfileUpdateParam;
import com.example.tech.folio.pojo.vo.ProfileVO;
import com.example.tech.folio.web.JsonResult;
import com.example.tech.folio.web.State;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/api/profile")
public class ProfileController {
    @Autowired
    private ProfileMapper profileMapper;

    // 处理查看个人资料请求的方法
    @GetMapping
    public JsonResult selectById() {
        long id = 1L; // ID固定为1
        Profile profile = profileMapper.selectById(id);
        if (profile == null) {
            throw new RuntimeException(State.ERR_NOT_FOUND);
        }
        return JsonResult.ok(profile);
    }

    // 处理查看个人资料请求的方法
    @GetMapping("/public")
    public JsonResult selectPublicById() {
        long id = 1L; // ID固定为1
        Profile profile = profileMapper.selectById(id);
        if (profile == null) {
            throw new RuntimeException(State.ERR_NOT_FOUND);
        }
        ProfileVO profileVO = new ProfileVO();
        BeanUtils.copyProperties(profile, profileVO);
        return JsonResult.ok(profileVO);
    }

    @PostMapping("/update")
    public JsonResult updateProfile(ProfileUpdateParam param) {
        // ID固定为1
        param.setId(1L);

        // 校验数据ID对应的数据是否存在
        Long id = param.getId();
        Profile profile = profileMapper.selectById(id);
        if (profile == null) {
            throw new RuntimeException(State.ERR_NOT_FOUND);
        }

        // 基于参数创建Profile对象
        BeanUtils.copyProperties(param, profile);

        // 调用ProfileMapper的“根据ID修改数据”方法
        profileMapper.updateById(profile);
        return JsonResult.ok();
    }
}